package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.BaseException;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        return addressBookMapper.list(BaseContext.getCurrentId());
    }

    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.add(addressBook);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void setDefault(AddressBook addressBook) {
        addressBook.setIsDefault(1);
        addressBookMapper.setDefault(addressBook);
        List<AddressBook> addressBooks = addressBookMapper.list(BaseContext.getCurrentId());
        for (AddressBook book : addressBooks) {
            if (!book.getId().equals(addressBook.getId())) {
                book.setIsDefault(0);
                addressBookMapper.setDefault(book);
            }
        }
    }

    @Override
    public AddressBook getDefault() {
        return addressBookMapper.getDefault();
    }

    @Override
    public void deleteById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        if (addressBook.getIsDefault() == 1) {
            throw new BaseException(MessageConstant.ADDRESS_BOOK_IS_DEFAULT);
        }
        addressBookMapper.deleteById(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }
}
